package com.hxgis.electronstarter.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hxgis.electronstarter.pojo.ElectronUrl;
import com.hxgis.electronstarter.pojo.UrlRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 赵恒
 * @date 2023/3/13
 */
@RestController
@RequestMapping("/electron")
@Slf4j
public class ElectronController {
    @Value("${electron.bat.dir}")
    private String electronBatDir;

    @Value("${electron.bat.filename}")
    private String electronBatFilename;

    @Autowired
    JdbcTemplate jdbcTemplate;

    ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 存储url的表名称
     */
    private String tableName = "ELECTRON_URL";

    Process process = null;

    /**
     * 启动 Electron 程序
     *
     * @return Map
     * @throws Exception Exception
     */
    @GetMapping("/start")
    public Map<String, String> startElectron() {
        System.out.println("接口/electron/start被调用");
        Map<String, String> map = new HashMap<>();
        map.put("message", "页面打开成功");
        // 启动Electron应用
        StringBuilder stringBuilder = new StringBuilder();

        File file = new File(electronBatDir + File.separator + electronBatFilename);
        if (!file.exists()) {
            map.put("message", "脚本文件未找到，请检查路径是否正确！");
            return map;
        }

        try {
            if (process != null) {
                process.destroy();
                process = null;
                log.info("process关闭");
            }
            log.info("开始执行指令，目录：{}, 命令：{}", electronBatDir, electronBatFilename);
            process = Runtime.getRuntime().exec("cmd /c cd " + electronBatDir + " && " + electronBatFilename);

            log.info("指令执行完毕");
        } catch (IOException e) {
            e.printStackTrace();
            map.put("message", e.getMessage());
        }
        log.info("执行结果：{}", stringBuilder);
        map.put("data", stringBuilder.toString());
        return map;
    }

    /**
     * 获取数据库中的URL列表
     *
     * @return URL集合
     */
    @GetMapping("/url/list")
    public List<String> getUrlList() {
        List<String> urls = jdbcTemplate.queryForList("SELECT url FROM " + tableName, String.class);
        try {
            log.info("url:{}", objectMapper.writeValueAsString(urls));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return urls;
    }

    /**
     * 查询数据库记录的集合
     *
     * @return
     */
    @GetMapping("electronUrl/list")
    public List<ElectronUrl> getElectronUrlList() {
        List<ElectronUrl> electronUrlList = jdbcTemplate.query("SELECT id, url, title FROM " + tableName, BeanPropertyRowMapper.newInstance(ElectronUrl.class));

        try {
            log.info("electronUrlList：{}", objectMapper.writeValueAsString(electronUrlList));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return electronUrlList;
    }

    /**
     * 向数据库中插入一条url
     *
     * @return
     */
    @PostMapping("/url/insert")
    public Map<String, String> insertUrl(@RequestBody UrlRequest urlRequest) {
        Map<String, String> map = new HashMap<>();
        jdbcTemplate.execute("INSERT INTO " + tableName + "(url, title) VALUES ('" + urlRequest.getUrl() + "','" + urlRequest.getTitle() + "');");
        map.put("message", "插入成功");
        return map;
    }

    /**
     * 根据ID删除对应的记录
     *
     * @param id
     * @return
     */
    @GetMapping("/url/delete")
    public Map<String, String> deleteUrl(int id) {
        Map<String, String> map = new HashMap<>();
        jdbcTemplate.execute("DELETE FROM " + tableName + " WHERE id = " + id);
        map.put("message", "删除成功");
        return map;
    }

    @PostMapping("/insertAndUpdate")
    public Map<String, String> updateBatch(@RequestBody List<ElectronUrl> electronUrlList) {
        // 批量修改或新增
        for (ElectronUrl electronUrl : electronUrlList) {
            if (electronUrl.getId() == null) {
                // 新增
                jdbcTemplate.execute("INSERT INTO " + tableName + "(url, title) VALUES ('" + electronUrl.getUrl() + "','" + electronUrl.getTitle() + "');");
            } else {
                // 修改
                jdbcTemplate.execute("UPDATE " + tableName + " SET url = '" + electronUrl.getUrl() + "', title='" + electronUrl.getTitle() + "' WHERE id=" + electronUrl.getId());
            }

        }
        Map<String, String> map = new HashMap<>();
        map.put("message", "保存成功");
        return map;
    }
}
